<template>
	<view class="login-container">
		<template>
			<view class="login-image">
				<!-- <image style="width:100%;height:100%;" src="@/static/img/loginbg.png" mode="scaleToFill"></image> -->
				<image class="logo-img" src="@/static/img/loginlogo.png" mode="scaleToFill"></image>
			</view>
			<view class="login-main">
				<view class="login-form">
					<view class="login-form-item">
						<view class="form-label">账号</view>
						<view class="form-content">
							<input type="text" placeholder-style="color:#CCCCCC" class="login-input" v-model="userName" placeholder="请输入账号"/>
						</view>
					</view>
					<view class="login-form-item">
						<view class="form-label">密码</view>
						<view class="form-content">
							<input v-if="type == 'password'" type="password" placeholder-style="color:#CCCCCC" class="login-input" v-model="password"
							 placeholder="请输入密码"/>
							<input v-if="type == 'text'" type="text" placeholder-style="color:#CCCCCC" class="login-input" v-model="password"
							 placeholder="请输入密码"/>
							<text v-show="passwordFlag" @tap="passwordFun" class="mima iconfont" :class="type == 'password'?'iconyincangmima':'iconmimakejian'"></text>
						</view>
					</view>
					<view class="remember-password">
						<view class="check-wrapper" @tap="isRembered = !isRembered">
							<view class="check-box">
								<view class="iconfont iconduihao" v-if="isRembered"></view>
							</view>
							<text>记住密码</text>
						</view>
						<span @tap="navTo('/packageA/pages/forgetPassword/forgetPassword')" style="color:#EA655E;">忘记密码？</span>
					</view>
					<view class="login-btn" @tap="handleLogin">
						登录
					</view>
					<view class="register" @tap="navTo('/packageA/pages/register/register')">
						<span>还没有账号?</span>
						<span class="register-text">去注册<i class="iconfont iconshuangjiantouyou"></i></span>
					</view>
					<view class="login-bottom">
						<view class="login-line">
							<view class="line"></view>
							<text>社交账户登录</text>
							<view class="line"></view>
						</view>
						<view class="other-login">
							
							<!-- #ifdef MP-WEIXIN -->
							<button v-if="canIUseGetUserProfile" @tap="getUserProfile"> 
								<image src="../../static/img/wx.png" mode=""></image>
							</button>
							<button v-else open-type="getUserInfo" @getuserinfo="wechatLogin"> 
								<image src="../../static/img/wx.png" mode=""></image>	
							 </button>
							<!-- #endif -->
							<!-- #ifdef APP-PLUS -->
							<button class="login-btn-submit" hover-class="btn-hover" @tap="wechatLogin">
								<image src="../../static/img/wx.png" mode=""></image>
							</button>
							
							<button  v-if="appleVisible" class="login-btn-submit" hover-class="btn-hover" @click="appleLogin">
								<image src="../../static/img/ios.png" mode=""></image>
							</button>
							<!-- #endif -->
							<!-- #ifdef H5 -->
							<button  class="login-btn-submit" hover-class="btn-hover" @click="$wechat.wxh5Login('snsapi_userinfo','pages/home/login')">
								<image src="../../static/img/wx.png" mode=""></image>
							</button>
							<!-- #endif -->
						</view>
					</view>
		
				</view>
			</view>
			<loading></loading>
			<tui-modal></tui-modal>
			<!--温馨提示-->
			<!-- #ifdef APP-PLUS -->
			<tui-modal :custom="true" :show="policyShow == '0'&&!showErrorModal" title="提示">
				<view class="login-modal-title">温馨提示</view>
				<view class="login-modal-content">
					<text>亲爱的用户，感谢您信任并使用DR云创！</text>
					<view>
						请充分阅读<text class="login-link" @tap="navTo('/packageA/pages/setupAll/userAgreement', {login: true})">《用户协议》</text>和<text class="login-link" @tap="navTo('/packageA/pages/setupAll/privacyPolicy', {login: true})">《隐私政策》</text>，点击“同意并继续”按钮代表您已同意前述协议及下列约定：为了给您提供浏览服务和保障账号安全，我们会申请系统权限收集设备信息；未经您同意，我们不会从第三方处获取、共享或向其提供您的信息；您可以查询、更正、删除您的个人信息，我们也提供账户注销的渠道。
					</view>
				</view>
				<view class="tui-modalBtn-box">
					<button class="login-modal-btn login-cancel-btn" @tap="closeModal">不同意</button>
					<button class="login-modal-btn login-sure-btn" @tap="clickSure">同意并继续</button>
				</view>
			</tui-modal>
			<!-- #endif -->
		</template>
		<view v-if="false" class="notH5Wx">
			请在微信浏览器中打开~
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
	} from 'vuex';
	
	export default {
		data() {
			return {
				policyShow:'',//用户阅读窗口显示
				appleVisible:false,
				isRembered: false,
				userName: '',
				password: '',
				passwordFlag: false,
				focusOne: false,
				focusTwo: false,
				disabledOne: true,
				disabledTwo: true,
				type: 'password',
				isWeixin: false,
				isH5Wx: '',
				canIUseGetUserProfile: false,
				userLoginClick: false,
			};
		},
		watch: {
			password(newValue) {
				if (newValue) {
					this.passwordFlag = true;
				} else {
					this.passwordFlag = false;
				}
			},
		},
		computed: {
			...mapState(['showErrorModal','loginInvalid']),
		},
		onLoad(options) {
			// #ifdef MP-WEIXIN
			if (wx.getUserProfile) {
				this.canIUseGetUserProfile = true;
			}
			// #endif
			// #ifndef H5
			this.isH5Wx = 'base';
			// #endif
			// #ifdef H5
			this.$wechat.noShare();
			this.isWeixin = this.$wechat.isWechat();
			this.isH5Wx = this.isWeixin ? 'base':'notH5';
			if(this.isWeixin){
				// 本地测H5请把这个放开，要不总往服务器跳
				// uni.setStorageSync('h5Openid', 'test')
				//未获得openid的情况获取openid
				if (!uni.getStorageSync('h5Openid')) {
					let code = this.$util.getUrlCode('code');
					if (code) {
						this.$http.getOpenId({code}).then((res) => {
							if (res.status == 0) {
								uni.setStorageSync('h5Openid', res.data);
							}
						});
					} else {
						//跳转微信获取code
						this.$wechat.wxh5Login('snsapi_base', 'pages/home/login');
					}
					
					
				} else {
					this.checkWeChatCode()//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				}
			}
			// #endif
			// #ifdef APP-PLUS
			if (uni.getSystemInfoSync().platform == "ios") {
				this.appleVisible=true
			}
			// #endif
			
			this.$nextTick(function(){
				console.log(uni.getStorageSync('userData'))
				const userData = JSON.parse(JSON.stringify(uni.getStorageSync('userData')));
				// debugger
				if(userData){
					this.userName=userData.agencyId
					this.password=userData.password
				}
				// uni.clearStorageSync('userData')
			})
			
		},
		onShow() {
			//页面加载完成，获取本地存储的用户名及密码
			const username = uni.getStorageSync('username');
			const password = uni.getStorageSync('password');
			const userData = uni.getStorageSync('userData');
			
			if(Object.keys(userData).length == 0) {
				if (username && password) {
					this.userName = username;
					this.password = password;
					this.isRembered = true;
				} else {
					this.userName = "";
					this.password = "";
					this.isRembered = false;
				}
			}
			// #ifdef APP-PLUS
			this.policyShow = uni.getStorageSync('isReadPolicy')?uni.getStorageSync('isReadPolicy'):'0';
			// #endif
		},
		methods: {
			clickSure() {
				uni.setStorageSync('isReadPolicy','1');
				this.policyShow = uni.getStorageSync('isReadPolicy');
			},
			closeModal() {
				uni.removeStorage('isReadPolicy');
				if (uni.getSystemInfoSync().platform == 'ios'){
				    plus.ios.import("UIApplication").sharedApplication().performSelector("exit");
				} else if (uni.getSystemInfoSync().platform == 'android'){
				    plus.runtime.quit();
				}
			},
			// #ifdef MP-WEIXIN
			getUserProfile(e) {
				if (this.userLoginClick) {
					return;
				}
				this.userLoginClick=true;
				const that = this;
			    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
			    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
			    wx.getUserProfile({
			      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
			      success: (info) => {
					  uni.login({
					  	provider: 'weixin',
					  	success: function(loginRes) {
							const params = {
								code: loginRes.code,
								iv: 'mp',
								encryptedData: 'mp',
								nickName: info.userInfo.nickName,
								avatarUrl: info.userInfo.avatarUrl
							};
							console.log(params)
							that.$util.setToken('');
							that.userLoginClick=false;
							that.$http.wxLogin(params).then(res => {
								if (res.status == 0) {
									that.$util.setToken(res.data.access_token);
									that.$util.setRefreshToken(res.data.refresh_token);
									that.$http.updateAuthorization({
										nickName: info.userInfo.nickName,
										avatarUrl: info.userInfo.avatarUrl,
										agencyId: that.$util.getInviterId(),
									}).then((childRes) => {
										if (childRes.status == 0) {
											that.loginAfter()
										} else {
											that.$util.setToken('');
										}
									}).catch(() => {
										that.$util.setToken('');
									});
								}
							})
					  	},
					  	fail: function(res) {
							that.userLoginClick=false;
						}
					  })
			      },
				  fail: function(res) {
				  	that.userLoginClick=false;
				  }
			    })
			},
			// #endif
			passwordFun() {
				this.type = this.type == 'password' ? 'text' : 'password';
			},
			backToPage() {
				// #ifdef H5
				const url = uni.getStorageSync('loginSuccessUrl');
				if (url) {
					uni.removeStorageSync('loginSuccessUrl');
					window.location.href = url;
				} else {
					uni.reLaunch({
						url: './home?initFlag=1'
					})
				}
				// #endif
				// #ifndef H5
				const pages = getCurrentPages();
				const prevPage = pages[pages.length - 2];
				if(prevPage) {
					uni.navigateBack({
						delta:1
					})
				} else {
					uni.reLaunch({
						url: './home?initFlag=1'
					})
				}
				// #endif
				// uni.clearStorageSync('userData')
			},
			loginAfter(){
				//获取用户身份
				this.$http.customerIdentity().then((res) => {
					if (res.status == 0) {
						this.backToPage();
						this.$util.storageIdentity(res);
					}
				})
				this.$util.getDictDataAll();
				this.$util.getRecordLogin();
			},
			handleLogin() {
				if (this.$util.isNullOrEmpty(this.userName)) {
					this.$util.toast('请输入账号');
					return;
				}
				if (this.$util.isNullOrEmpty(this.password)) {
					this.$util.toast('请输入密码');
					return;
				}
				uni.removeStorageSync('userData')
				const data = {
					username: this.userName.trim(),
					password: this.password,
				};
				// #ifdef MP-WEIXIN
				data.code = 'mp'
				// #endif
				// #ifdef H5
				data.code = 'su'
				// #endif
				this.$util.setToken('');
				this.$http.login(data).then(res => {
					if (res.status == 0) {
						this.$util.setToken(res.data.access_token);
						this.$util.setRefreshToken(res.data.refresh_token);
						// #ifdef APP-PLUS
						this.updateCid()
						// #endif
						this.loginAfter();
						//登录成功将用户名密码存储到用户本地
						if (this.isRembered) {
							//勾选“记住密码”
							uni.setStorageSync('username', this.userName);
							uni.setStorageSync('password', this.password);
							
						} else {
							//没有勾选“记住密码”
							uni.removeStorageSync('username');
							uni.removeStorageSync('password');
							this.userName = "";
							this.password = "";
						}

					}
				})
			},
// apple登陆
			appleLogin(){
				// #ifdef APP-PLUS
				uni.getProvider({
					service: 'oauth',
					success: (res) =>{
						if (~res.provider.indexOf('apple')) {
							uni.login({
								provider: 'apple',
								success:  (loginRes) => {
									uni.getUserInfo({  
										provider: 'apple',  
										success:(info) => {  
											// 获取用户信息成功 
											 const appleId = info.userInfo.openId
											 this.$util.setToken('');
											 this.$http.appAppleLogin({appleId}).then(res => {
											 	if (res.status === 0) {
											 		let {access_token,refresh_token,token_type,userId,userName} = res.data
											 		this.$util.setToken(access_token)
											 		this.$util.setToken(access_token);
											 		this.$util.setRefreshToken(refresh_token);
											 		this.$http.updateAuthorization({
											 			agencyId: this.$util.getInviterId(),
											 		}).then((childRes) => {
											 			if (childRes.status == 0) {
											 				// #ifdef APP-PLUS
											 				this.updateCid()
											 				// #endif
											 				this.loginAfter();
											 			} else {
											 				this.$util.setToken('');
											 			}
											 		}).catch(() => {
											 			this.$util.setToken('');
											 		})
													
											 	}else{
													
												}
											 })
										}  
									})  
								}
							});
						} else {
							uni.showToast({
								title: '该设备可能是模拟器或者无效的苹果设备',
								icon: "none"
							});
						}
					}
				});
				//#endif
			},
			// 点击微信图标
			wechatLogin() {
				// 获取用户名  获取性别 获取头像 获取js_code去换取后台返回的openID
				// #ifdef MP-WEIXIN
				this.mpWxLogin();
				//#endif

				// #ifdef APP-PLUS
				this.appWxLogin();
				//#endif
			},
			
			// 小程序微信登录
			mpWxLogin() {
				const that = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						// 获取用户信息
						uni.getUserInfo({
							provider: 'weixin',
							success: function(info) {
								const params = {
									code: loginRes.code,
									iv: info.iv,
									encryptedData: info.encryptedData,
									nickName: info.userInfo.nickName,
									avatarUrl: info.userInfo.avatarUrl
								};
								console.log(params)
								that.$util.setToken('');
								that.$http.wxLogin(params).then(res => {
									if (res.status == 0) {
										that.$util.setToken(res.data.access_token);
										that.$util.setRefreshToken(res.data.refresh_token);
										that.$http.updateAuthorization({
											nickName: info.userInfo.nickName,
											avatarUrl: info.userInfo.avatarUrl,
											agencyId: that.$util.getInviterId(),
										}).then((childRes) => {
											if (childRes.status == 0) {
												that.loginAfter()
											} else {
												that.$util.setToken('');
											}
										}).catch(() => {
											that.$util.setToken('');
										});
									}
								})
							},
							fail: function(res) {}
						})
					},
					fail: function(res) {}
				})
			},
			// app端微信登录
			appWxLogin() {
				const that = this
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									// 获取用户信息
									uni.getUserInfo({
										provider: 'weixin',
										success: (info) => {
											const params = {
												appOpenId: loginRes.authResult.openid,
												unionId: loginRes.authResult.unionid,
												nickName: info.userInfo.nickName,
												avatarUrl: info.userInfo.avatarUrl
											};
											that.$util.setToken('');
											that.$http.appWxLogin(params).then(res => {
												if (res.status == 0) {
													that.$util.setToken(res.data.access_token);
													that.$util.setRefreshToken(res.data.refresh_token);
													that.$http.updateAuthorization({
														nickName: info.userInfo.nickName,
														avatarUrl: info.userInfo.avatarUrl,
														agencyId: that.$util.getInviterId(),
													}).then((childRes) => {
														if (childRes.status == 0) {
															// #ifdef APP-PLUS
															that.updateCid()
															// #endif
															that.loginAfter();
														} else {
															that.$util.setToken('');
														}
													}).catch(() => {
														that.$util.setToken('');
													})
												}
											})
										},
										fail: () => {
											uni.showToast({
												title: "微信登录授权失败",
												icon: "none"
											});
										}
									})
								}
							});
						} else {
							uni.showToast({
								title: '请先安装微信或升级版本',
								icon: "none"
							});
						}
					}
				});
			},
			// #ifdef H5
			//检查浏览器地址栏中微信接口返回的code
			checkWeChatCode() {
				let code = this.$util.getUrlCode('code')
				if (code) {
					if (!this.$util.getToken()) {
						this.getOpenidAndUserinfo(code);
					} else {
						this.backToPage();
					}
				}
			},
			//把code传递给后台接口，静默登录 "041CBv100L9boL1ArF3009C3d83CBv1d"
			getOpenidAndUserinfo(code) {
				this.$util.setToken('');
				this.$http.h5WxLogin({code}).then(res => {
					console.log("-----***h5WxLogin res: ",res);
					if (res.status === 0) {
						let {access_token,refresh_token,token_type,userId,userName} = res.data
						this.$util.setToken(access_token)
						this.$util.setRefreshToken(refresh_token);
						this.$http.updateAuthorization({
							agencyId: this.$util.getInviterId(),
						}).then((childRes) => {
							if (childRes.status == 0) {
								// #ifdef APP-PLUS
								this.updateCid()
								// #endif
								this.loginAfter();
							} else {
								this.$util.setToken('');
							}
						}).catch(() => {
							this.$util.setToken('');
						})
					}
				})
			},
			// #endif
			
			clearuserName() {
				this.userName = '';
			},
			clearPassword() {
				this.password = '';
			},
			// #ifdef APP-PLUS
			updateCid() {
				let cid = plus.push.getClientInfo().clientid;
				
				if(uni.getSystemInfoSync().platform === 'android'){
					cid = `${cid}_android`
				}else{
					cid = `${cid}_ios`
				}
				console.log(cid)
				this.$http.updateCid({cid});
			},
			// #endif
		},
	};
</script>

<style lang="scss">
	.notH5Wx {
		width: 100%;
		height: 100vh;
		background: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.login-modal-title {
		text-align: center;
		font-size: 34rpx;
		color: #111;
		padding-top: 10rpx;
		font-weight: bold;
	}
	
	.login-modal-content {
		text-align: justify;
		color: #999;
		font-size: 28rpx;
		padding-top: 20rpx;
		padding-bottom: 60rpx;
		max-height: 70vh;
		overflow-y: auto;
	}
	.tui-modalBtn-box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between
	}
	.login-modal-btn {
		width: 240rpx;
		height: 80rpx;
		line-height: 80rpx;
		position: relative;
		border-radius: 50px;
		font-size: 30rpx;
		overflow: visible;
		margin:0 12rpx;
	}
	.login-link {
		text-decoration: underline;
		color: #EA655E;
	}
	.login-cancel-btn {
		color: #999999;
		background: #F5F5F5 !important;
	}
	.login-sure-btn {
		color: #fff;
		background: linear-gradient(151deg, #F69E97 0%, #EA655E 100%);
	}
	.login-container {
		width: 100%;
		height: 100vh;
		background: #fff;
		display: flex;
		flex-direction: column;

		.placeholder {
			color: #CCCCCC;
		}

		.login-image {
			display: flex;
			justify-content: center;
			align-items: center;
			padding-top: 54rpx;

			.logo-img {
				width: 280rpx;
				height: 280rpx;
			}
		}

		.login-main {
			flex: 1;
			padding: 0 32rpx;

			.login-form {
				height: 100%;
				display: flex;
				flex-direction: column;

				.login-form-item {
					padding: 0 16rpx;

					.form-label {
						font-size: 32rpx;
						color: #999999;
						margin-bottom: 20rpx;
						padding-left: 16rpx;
					}
					
					.user-content {
						padding-left: 50rpx !important;
					}

					.form-content {
						height: 100rpx;
						border-radius: 16rpx;
						font-size: 28rpx;
						color: #111111;
						padding: 0 32rpx;
						display: flex;
						align-items: center;
						margin-bottom: 24rpx;
						box-shadow: 0rpx 12rpx 24rpx 0rpx #EBECF2;

						.login-input {
							flex: 1;
							color: #111111;
							font-size: 28rpx;
						}

						.mima {
							color: #111111;
							width: 55rpx;
							font-size: 36rpx;
							text-align: right;
							// padding: 20rpx;

						}
					}
				}

				.remember-password {
					display: flex;
					font-size: 28rpx;
					justify-content: space-between;
					margin: 0rpx 0 50rpx 0;
					align-items: center;
					padding: 0 10rpx;
					
					.check-wrapper {
						display: flex;
						align-items: center;
						.check-box {
							width: 28rpx;
							height: 28rpx;
							background: #FFFFFF;
							border-radius: 8rpx;
							border: 2rpx solid #CCCCCC;
							margin-right: 16rpx;
							.iconfont {
								font-size: 20rpx;
								color: #EA655E;
							}
						}
					}
				}

				.login-btn {
					font-size: 38rpx;
					text-align: center;
					height: 100rpx;
					line-height: 100rpx;
					color: #fff;
					background: linear-gradient(151deg, #F69E97 0%, #EA655E 100%);
					box-shadow: 0px 4rpx 40rpx 0px rgba(83, 0, 0, 0.24);
					border-radius: 50rpx;
				}

				.register {
					font-size: 24rpx;
					display: flex;
					justify-content: center;
					margin: 40rpx 0 70rpx 0;
					color: #CCCCCC;
				}
				
				.register-text {
					display: flex;
					align-items: center;
					color:#EA655E;
					margin-left: 14rpx;
					.iconfont {
						margin-left: 4rpx;
						font-size: 24rpx;
					}
				}

				.login-line {
					width: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
					
					text {
						color:#CCCCCC;
						font-size:24rpx;
					}

					.line {
						width: 248rpx;
						height: 1px;
						background: #D8D8D8;
					}
				}

				.other-login {
					flex: 1;
					align-items: center;
					display: flex;
					justify-content: center;
					// margin-top: 32rpx;
					min-height: 100rpx;
					image {
						width: 100rpx;
						height: 100rpx;
					}
					
					.login-btn-submit{
						margin: 0rpx 54rpx;
					}

				}

				.login-bottom {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-around;
				}
			}

		}
	}
</style>
